package com.liuhangkai.firstpro.controller;

import com.liuhangkai.firstpro.config.CustomException;
import com.liuhangkai.firstpro.jwt.JwtToken;
import com.liuhangkai.firstpro.model.Author;
import com.liuhangkai.firstpro.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/a")
public class StuVC {
    @Autowired
    StuService stuService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/test1")
    public String xxx(HttpServletRequest servletRequest, String username,String name){
        Object flag = servletRequest.getAttribute("flag");
        System.out.println("=====flag====");
        System.out.println(servletRequest.getHeader("token"));
        System.out.println(flag);
        return  "helloword"+new Date().getTime() +username+"-"+name;
    }

    @GetMapping("/lua")
    public void xx1(){
        DefaultRedisScript redisScript = new DefaultRedisScript<>();
           // 指定 lua 脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("redis/redis_lock4.lua")));
        redisScript.setResultType(Long.class);
        // 参数一：redisScript，参数二：key列表，参数三：arg（可多个）
        Object result = redisTemplate.execute(redisScript, Collections.singletonList("lockKey"),"100");
        System.out.println(result);
    }

    @GetMapping("/mongo")
    public void xx2(){
//        Author a = new Author();
//        a.setBio("zhangsan");
//        a.setUsername("lisi");
//        a.setPassword("kaiwanxiao");
//        a.setFavouriteSection("meili");
//        mongoTemplate.insert(a);
        Query q = new Query();
        q.addCriteria(Criteria.where("bio").is("zhangsan"));
        List<Author> authors = mongoTemplate.find(q, Author.class);
        System.out.println(authors);

    }
}
